<?php
namespace App\Controllers;

use App\Models\Message;
use App\Models\Group;
use App\Models\User;
use App\Models\GroupMember;
use App\Models\MessageRead;
use App\Models\Friend;
use App\Config\JwtConfig;

class ChatController {
    private $messageModel;
    private $groupModel;
    private $userModel;
    private $groupMemberModel;
    private $messageReadModel;
    private $friendModel;

    public function __construct() {
        $this->messageModel = new Message();
        $this->groupModel = new Group();
        $this->userModel = new User();
        $this->groupMemberModel = new GroupMember();
        $this->messageReadModel = new MessageRead();
        $this->friendModel = new Friend();
    }

    // 统一响应格式
    private function response($code = 0, $data = [], $message = 'success') {
        http_response_code($code === 0 ? 200 : 400);
        header('Content-Type: application/json');
        echo json_encode([
            'code' => $code,
            'data' => $data,
            'message' => $message
        ]);
    }

    /**
     * 获取所有会话列表（包括单聊和群聊）
     */
    public function getConversations() {
        $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $token = str_replace('Bearer ', '', $token);
        $userId = JwtConfig::getUserIdFromToken($token);

        if (!$userId) {
            return $this->response(401, [], '未授权');
        }

        $page = $_GET['page'] ?? 1;
        $pageSize = $_GET['page_size'] ?? 20;
        $offset = ($page - 1) * $pageSize;

        // 获取单聊会话
        $singleChatConversations = $this->getSingleChatConversations($userId);
        
        // 获取群聊会话
        $groupChatConversations = $this->getGroupChatConversations($userId);
        
        // 合并会话并按最后消息时间排序
        $allConversations = array_merge($singleChatConversations, $groupChatConversations);
        usort($allConversations, function($a, $b) {
            return $b['last_message_time'] - $a['last_message_time'];
        });
        
        // 分页处理
        $total = count($allConversations);
        $paginatedConversations = array_slice($allConversations, $offset, $pageSize);
        
        return $this->response(0, [
            'conversations' => $paginatedConversations,
            'total' => $total,
            'page' => $page,
            'page_size' => $pageSize
        ], 'success');
    }

    /**
     * 获取单聊会话列表
     */
    private function getSingleChatConversations($userId) {
        error_log("开始获取用户 $userId 的单聊会话");
        
        // 从模型获取单聊会话列表
        $conversationsData = $this->messageModel->getSingleChatConversations($userId);
        error_log("从模型获取到 " . count($conversationsData) . " 条单聊会话数据");
        
        $conversations = [];
        foreach ($conversationsData as $index => $conv) {
            // 修复1: 确保ID是整数
            $contactId = is_numeric($conv['id']) ? (int)$conv['id'] : 0;
            if ($contactId <= 0) {
                error_log("警告: 无效的联系人ID: " . json_encode($conv['id']));
                continue;
            }
            
            error_log("处理会话 #" . ($index + 1) . " - 联系人ID: $contactId, 未读数: " . $conv['unread_count']);
            
            // 获取联系人信息
            $contact = $this->userModel->findById($contactId);
            
            // 修复2: 区分数据库错误和用户不存在
            if ($contact === false) {
                error_log("数据库错误: 无法查询联系人ID $contactId");
                continue; // 跳过当前会话，但继续处理其他会话
            }
            
            if (!$contact) {
                error_log("警告: 联系人ID $contactId 不存在");
                // 即使联系人不存在，也显示会话（使用默认信息）
                $contactInfo = [
                    'name' => '未知用户',
                    'avatar' => ''
                ];
            } else {
                // 修复3: 使用正确的字段名（username 而不是 nickname）
                $contactInfo = [
                    'name' => $contact['username'] ?? '未知用户',  // 使用username字段
                    'avatar' => $contact['avatar_url'] ?? '',      // 使用avatar_url字段
                    'phone' => $contact['phone'] ?? '',
                    'email' => $contact['email'] ?? '',
                ];
            }
            
            $conversations[] = [
                'type' => 1, // 单聊
                'id' => $contactId,
                'name' => $contactInfo['name'],
                'avatar' => $contactInfo['avatar'],
                'phone' => $contactInfo['phone'],
                'email' => $contactInfo['email'],
                'last_message' => [
                    'message_id' => $conv['last_message_id'],
                    'content_type' => $conv['content_type'],
                    'content' => $conv['content'],
                    'timestamp' => $conv['timestamp']
                ],
                'unread_count' => $conv['unread_count'],
                'last_message_time' => $conv['timestamp']
            ];
        }
        
        error_log("最终返回 " . count($conversations) . " 条单聊会话");
        return $conversations;
    }

    /**
     * 获取群聊会话列表
     */
    private function getGroupChatConversations($userId) {
        // 获取用户加入的所有群组
        $groups = $this->groupMemberModel->getUserGroups($userId);
        
        $conversations = [];
        foreach ($groups as $group) {
            $groupId = $group['id'];
            
            // 获取群组最后一条消息
            $lastMessage = $this->messageModel->getGroupLastMessage($groupId);
            
            if (!$lastMessage) {
                continue;
            }
            
            // 获取未读消息数量
            $unreadCount = $this->messageReadModel->getUnreadCountForGroup($userId, $groupId);
            
            $conversations[] = [
                'type' => 2, // 群聊
                'id' => $groupId,
                'name' => $group['name'],
                'avatar' => $group['avatar_url'] ?? '',
                'announcement' => $group['announcement'] ?? '',
                'last_message' => [
                    'message_id' => $lastMessage['message_id'],
                    'content_type' => $lastMessage['content_type'],
                    'content' => $lastMessage['content'],
                    'timestamp' => $lastMessage['timestamp']
                ],
                'unread_count' => $unreadCount,
                'last_message_time' => $lastMessage['timestamp']
            ];
        }
        
        return $conversations;
    }
    
    /**
     * 获取联系人列表（好友列表）
     */
    public function getContacts() {
        $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $token = str_replace('Bearer ', '', $token);
        $userId = JwtConfig::getUserIdFromToken($token);

        if (!$userId) {
            return $this->response(401, [], '未授权');
        }

        $page = $_GET['page'] ?? 1;
        $pageSize = $_GET['page_size'] ?? 20;

        // 获取好友列表
        $friends = $this->friendModel->getFriends($userId, $page, $pageSize);
        
        return $this->response(0, ['friends' => $friends], 'success');
    }

    /**
     * 获取群聊列表
     */
    public function getGroups() {
        $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $token = str_replace('Bearer ', '', $token);
        $userId = JwtConfig::getUserIdFromToken($token);

        if (!$userId) {
            return $this->response(401, [], '未授权');
        }

        $page = $_GET['page'] ?? 1;
        $pageSize = $_GET['page_size'] ?? 20;

        // 获取用户加入的群组
        $groups = $this->groupMemberModel->getUserGroups($userId, $page, $pageSize);
        
        return $this->response(0, ['groups' => $groups], 'success');
    }

    // 发送消息
    public function sendMessage() {
        $data = json_decode(file_get_contents("php://input"), true);
        // 获取并处理Authorization头
        $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        if (empty($token)) {
            return $this->response(401, [], '未授权，无token');
        }
        $token = str_replace('Bearer ', '', $token);
        $userId = JwtConfig::getUserIdFromToken($token);
        if (!$userId) {
            return $this->response(401, [], '未授权');
        }

        // 验证请求数据
        if (empty($data['receiver_type']) || empty($data['receiver_id']) || !isset($data['content_type']) || !isset($data['content'])) {
            return $this->response(1001, [], '参数错误');
        }

        $receiverType = $data['receiver_type'];
        $receiverId = $data['receiver_id'];
        $contentType = $data['content_type'];
        $content = $data['content'];

        // 检查接收方是否存在
        if ($receiverType == 1) { // 单聊
            $user = $this->userModel->findById($receiverId);
            if (!$user) {
                return $this->response(1002, [], '用户不存在');
            }
        } elseif ($receiverType == 2) { // 群聊
            $group = $this->groupModel->findById($receiverId);
            if (!$group) {
                return $this->response(1003, [], '群组不存在');
            }
            // 检查当前用户是否在群内
            $isMember = $this->groupMemberModel->isMember($receiverId, $userId);
            if (!$isMember) {
                return $this->response(1004, [], '你不是该群成员');
            }
        } else {
            return $this->response(1005, [], '接收方类型错误');
        }

        // 生成唯一消息ID
        $messageId = uniqid('msg_', true);
        $timestamp = time() * 1000; // 毫秒时间戳

        // 保存消息
        $this->messageModel->message_id = $messageId;
        $this->messageModel->sender_id = $userId;
        $this->messageModel->receiver_type = $receiverType;
        $this->messageModel->receiver_id = $receiverId;
        $this->messageModel->content_type = $contentType;
        $this->messageModel->content = $content;
        $this->messageModel->timestamp = $timestamp;

        try {
            if ($this->messageModel->save()) {
                return $this->response(0, [
                    'message_id' => $messageId,
                    'timestamp' => $timestamp
                ], '发送成功');
            } else {
                return $this->response(1006, [], '发送失败');
            }
        } catch (\Exception $e) {
            error_log("消息保存失败: " . $e->getMessage());
            return $this->response(1006, [], '发送失败');
        }
    }

    // 获取历史消息
    public function getHistory() {
        $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $token = str_replace('Bearer ', '', $token);
        $userId = JwtConfig::getUserIdFromToken($token);

        if (!$userId) {
            return $this->response(401, [], '未授权');
        }

        $receiverType = $_GET['receiver_type'] ?? 0;
        $receiverId = $_GET['receiver_id'] ?? 0;
        $page = $_GET['page'] ?? 1;
        $pageSize = $_GET['page_size'] ?? 20;
        $beforeTimestamp = $_GET['before_timestamp'] ?? null;

        if ($receiverType == 0 || $receiverId == 0) {
            return $this->response(1001, [], '参数错误');
        }

        // 分页查询
        $offset = ($page - 1) * $pageSize;
        $messages = $this->messageModel->getHistory($userId, $receiverType, $receiverId, $beforeTimestamp, $offset, $pageSize);

        // 当获取群消息时，标记最后一条消息为已读（表示用户已经查看该群组）
        if (is_null($beforeTimestamp)) { // 仅当获取最新消息（首次加载）时标记
            if ($receiverType == 2 && !empty($messages)) {
                // 群聊：标记最新消息（第一条）为已读
                $latestMessage = $messages[0];
                $this->messageReadModel->markAsRead($latestMessage['message_id'], $userId, $receiverId);
            } else if ($receiverType == 1) {
                // 单聊：标记当前会话所有未读消息为已读
                $this->messageModel->markAsRead($userId, $receiverId);
            }
        }
        
        return $this->response(0, ['messages' => $messages], 'success');
    }

    // 标记单聊消息为已读
    public function markAsRead() {
        $data = json_decode(file_get_contents("php://input"), true);
        $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $token = str_replace('Bearer ', '', $token);
        $userId = JwtConfig::getUserIdFromToken($token);

        if (!$userId) {
            return $this->response(401, [], '未授权');
        }

        $receiverId = $data['receiver_id'] ?? 0;
        if ($receiverId == 0) {
            return $this->response(1001, [], '参数错误');
        }

        // 更新当前用户与receiverId之间的所有未读消息为已读
        if ($this->messageModel->markAsRead($userId, $receiverId)) {
            return $this->response(0, [], '标记成功');
        } else {
            return $this->response(1002, [], '标记失败');
        }
    }

    // 标记群聊消息为已读
    public function markGroupMessageAsRead() {
        $data = json_decode(file_get_contents("php://input"), true);
        $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $token = str_replace('Bearer ', '', $token);
        $userId = JwtConfig::getUserIdFromToken($token);

        if (!$userId) {
            return $this->response(401, [], '未授权');
        }

        $messageId = $data['message_id'] ?? '';
        $groupId = $data['group_id'] ?? 0;

        if (empty($messageId) || $groupId == 0) {
            return $this->response(1001, [], '参数错误');
        }

        // 检查消息是否存在，且属于该群组
        $message = $this->messageModel->findByMessageId($messageId);
        if (!$message || $message['receiver_type'] != 2 || $message['receiver_id'] != $groupId) {
            return $this->response(1002, [], '消息不存在或不属于该群组');
        }

        // 检查用户是否在群内
        if (!$this->groupMemberModel->isMember($groupId, $userId)) {
            return $this->response(1003, [], '你不是该群成员');
        }

        // 标记为已读
        if ($this->messageReadModel->markAsRead($messageId, $userId, $groupId)) {
            return $this->response(0, [], '标记成功');
        } else {
            return $this->response(1004, [], '标记失败');
        }
    }

    // 获取未读消息数量
    public function getUnreadCount() {
        $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $token = str_replace('Bearer ', '', $token);
        $userId = JwtConfig::getUserIdFromToken($token);

        if (!$userId) {
            return $this->response(401, [], '未授权');
        }

        // 单聊未读消息数量
        $singleChatCounts = $this->messageModel->getUnreadCount($userId);
        
        // 群聊未读消息数量
        $groupUnreadCounts = [];
        // 获取用户加入的所有群组
        $userGroups = $this->groupMemberModel->getUserGroups($userId);
        
        foreach ($userGroups as $group) {
            $groupId = $group['id'];
            $count = $this->messageReadModel->getUnreadCountForGroup($userId, $groupId);
            if ($count > 0) {
                $groupUnreadCounts[$groupId] = $count;
            }
        }

        return $this->response(0, [
            'single_chat_unreads' => $singleChatCounts,
            'group_unreads' => $groupUnreadCounts
        ], 'success');
    }

    // 撤回消息
    public function revokeMessage() {
        $data = json_decode(file_get_contents("php://input"), true);
        $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $token = str_replace('Bearer ', '', $token);
        $userId = JwtConfig::getUserIdFromToken($token);

        if (!$userId) {
            return $this->response(401, [], '未授权');
        }

        $messageId = $data['message_id'] ?? '';
        if (empty($messageId)) {
            return $this->response(1001, [], '消息ID不能为空');
        }

        // 检查消息是否存在，且是当前用户发送的
        $message = $this->messageModel->findByMessageId($messageId);
        if (!$message || $message['sender_id'] != $userId) {
            return $this->response(1002, [], '消息不存在或无权操作');
        }

        // 检查是否在撤回时间范围内（5分钟内）
        $currentTime = time() * 1000;
        $timeDiff = $currentTime - $message['timestamp'];
        if ($timeDiff > 5 * 60 * 1000) {
            return $this->response(1003, [], '超过撤回时间');
        }

        // 撤回消息
        $this->messageModel->revoke($messageId);

        return $this->response(0, [], '撤回成功');
    }

    /**
     * 搜索消息接口
     * 支持按时间范围、关键词搜索当前用户参与的消息
     */
    public function searchMessages() {
        $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $token = str_replace('Bearer ', '', $token);
        $userId = JwtConfig::getUserIdFromToken($token);

        if (!$userId) {
            return $this->response(401, [], '未授权');
        }

        // 获取搜索参数
        $startTime = $_GET['start_time'] ?? null;
        $endTime = $_GET['end_time'] ?? null;
        $keyword = $_GET['keyword'] ?? null;
        $page = max(1, (int)($_GET['page'] ?? 1));
        $pageSize = min(100, max(1, (int)($_GET['page_size'] ?? 20))); // 限制每页数量范围

        // 类型转换
        if ($startTime !== null) $startTime = (int)$startTime;
        if ($endTime !== null) $endTime = (int)$endTime;

        // 调用模型搜索
        $messages = $this->messageModel->searchMessages($userId, $startTime, $endTime, $keyword, $page, $pageSize);

        return $this->response(0, [
            'messages' => $messages,
            'page' => $page,
            'page_size' => $pageSize
        ], 'success');
    }
}